import uuid
import tos
import settings


class ObjectStorage:
    def __init__(self, access_key=None, secret_key=None, endpoint_url=None, region=None, bucket_name=None):
        self.access_key = access_key if access_key else settings.tos_ak
        self.secret_key = secret_key if secret_key else settings.tos_sk
        self.endpoint_url = endpoint_url if endpoint_url else settings.tos_endpoint
        self.region = region if region else settings.tos_region
        self.bucket_name = bucket_name if bucket_name else bucket_name
        self.client = tos.TosClientV2(self.access_key, self.secret_key, self.endpoint_url, self.region)

    def create_bucket(self):
        resp = self.client.create_bucket(self.bucket_name)
        assert resp.status_code == 200

    def put_object(self, remote_path):
        try:
            resp = self.client.put_object(self.bucket_name, remote_path, content="123")
            assert resp.status_code == 200
        except Exception as e:
            print("上传图片到火山云对象存储失败:", e)
            return None

    def upload_file(self, object_key, local_path):
        try:
            resp = self.client.upload_file(self.bucket_name, object_key, local_path)
            assert resp.status_code == 200
            return settings.tos_base_url+object_key
        except Exception as e:
            print("上传图片到火山云对象存储失败:", e)
            return None

    def get_object(self, object_key):
        try:
            resp = self.client.get_object(self.bucket_name, object_key)
            assert resp.status_code == 200
            return resp
        except Exception as e:
            print("上传图片到火山云对象存储失败:", e)
            return None


if __name__ == '__main__':
    oss = ObjectStorage(bucket_name='planner')
    # oss.create_bucket()

    # local_image_path = "/Users/yaodong/Downloads/echarts.png"
    # suffix = local_image_path.split('/')[-1]
    # # object_key = str(uuid.uuid4()).replace("-", "") + "." + suffix  # 生成唯一的文件名
    # remote_path = "a/" + suffix
    # # oss.upload_file(remote_path)
    # oss.put_object(remote_path)

    local_image_path = "/Users/yaodong/Downloads/echarts.png"
    suffix = local_image_path.split('/')[-1]
    # object_key = str(uuid.uuid4()).replace("-", "") + "." + suffix  # 生成唯一的文件名
    remote_path = "a/" + suffix
    # oss.upload_file(remote_path)
    oss.upload_file(remote_path, local_image_path)

    # print(str(oss.get_object("a/echarts.png")))
